package com.xhb.campusservices.controller;

import com.xhb.campusservices.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@Slf4j
@Controller
public class FileController {
    @Value("${upload.dir}")
    private String realPath;

    @PostMapping("/upload")
    public String upload(@RequestPart("imageFile") MultipartFile headerImg, Model model) throws IOException {

        log.info("上传的信息：headerImg={}", headerImg.getSize());
        log.info("上传的信息：getInputStream={}", headerImg.getInputStream());
        String filePath = realPath + "default.jpg";
        MultipartFile head2 = new MockMultipartFile("default.jpg", new FileInputStream(filePath));
        if (!headerImg.isEmpty()) {
            //保存到文件服务器
            String originalFilename = headerImg.getOriginalFilename();
            System.out.println(originalFilename);
            //判断文件类型
            String allowType = "gif,jpg,png,jpeg";
            //文件非空
            if (!("").equals(originalFilename.trim()) && originalFilename.length() > 0) {
                System.out.println("trim:" + originalFilename.trim());
                String ex = (String) originalFilename.subSequence(originalFilename.lastIndexOf(".") + 1,
                        originalFilename.length());
                if (allowType.indexOf(ex.toLowerCase()) < 0) {
                    System.out.println("文件类型不对");
                    return "index";
                }
                String newFileName = "aa";
                headerImg.transferTo(new File(realPath + newFileName + ".jpg"));
            }
        }
        model.addAttribute("msg", "大家好,320");
        return "index";
    }


    @PostMapping("/upload2")
    public String upload2(@RequestPart("imageFile") MultipartFile headerImg, Model model) throws IOException {

        log.info("上传的信息：headerImg={}", headerImg.getSize());

        //图片所在路径
        BufferedImage read = ImageIO.read(headerImg.getInputStream());
        //原始图片的长度和宽度
      /*  int height = read.getHeight();
        int width = read.getWidth();
        System.out.println(height+","+width);*/

        //通过固定长度压缩
            /*int doWithHeight = 100;
            int dowithWidth = 300;*/

        //通过比例压缩
        float scale = 0.5f;
        //压缩之后的长度和宽度
        int height = (int) (scale * read.getHeight());
        int width = (int) (scale * read.getWidth());
        BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        finalImage.getGraphics().drawImage(read.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        //图片输出路径，以及图片名
        FileOutputStream fileOutputStream = new FileOutputStream(realPath+"aa.jpg");
        ImageIO.write(finalImage,"jpg",fileOutputStream);
        fileOutputStream.close();

        System.out.println(finalImage);
        if (!headerImg.isEmpty()) {
            //保存到文件服务器
            String originalFilename = headerImg.getOriginalFilename();
            System.out.println(originalFilename);
            //判断文件类型
            String allowType = "gif,jpg,png,jpeg";
            //文件非空
            if (!("").equals(originalFilename.trim()) && originalFilename.length() > 0) {
                System.out.println("trim:" + originalFilename.trim());
                String ex = (String) originalFilename.subSequence(originalFilename.lastIndexOf(".") + 1,
                        originalFilename.length());
                if (allowType.indexOf(ex.toLowerCase()) < 0) {
                    System.out.println("文件类型不对");
                    return "index";
                }
                String newFileName = "xiaoxia";
                headerImg.transferTo(new File(realPath + newFileName + ".jpg"));
            }
        }
        model.addAttribute("msg", "大家好,320");
        return "index";
    }

    @PostMapping("/upload3")
    public String upload3(@RequestPart("imageFile") MultipartFile headerImg, Model model) throws IOException {

        log.info("上传的信息：headerImg={}", headerImg.getSize());
        if (!headerImg.isEmpty()) {
            //保存到文件服务器
            String originalFilename = headerImg.getOriginalFilename();
            System.out.println(originalFilename);
            //判断文件类型
            String allowType = "gif,jpg,png,jpeg";
            //文件非空
            if (!("").equals(originalFilename.trim()) && originalFilename.length() > 0) {
                System.out.println("trim:" + originalFilename.trim());
                String ex = (String) originalFilename.subSequence(originalFilename.lastIndexOf(".") + 1,
                        originalFilename.length());
                if (allowType.indexOf(ex.toLowerCase()) < 0) {
                    System.out.println("文件类型不对");
                    return "index";
                }
               /* //图片所在路径
                BufferedImage read = ImageIO.read(headerImg.getInputStream());
                //通过比例压缩
                float scale = 0.5f;
                //压缩之后的长度和宽度
                int height = (int) (scale * read.getHeight());
                int width = (int) (scale * read.getWidth());
                BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                finalImage.getGraphics().drawImage(read.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
               */
                if(headerImg.getSize()>1000000){
                    BufferedImage finalImage = reduce(ImageIO.read(headerImg.getInputStream()),0.5f);
                    //图片输出路径，以及图片名
                    FileOutputStream fileOutputStream = new FileOutputStream(realPath+"aa.jpg");
                    ImageIO.write(finalImage,"jpg",fileOutputStream);
                    fileOutputStream.close();
                }else{
                    headerImg.transferTo(new File(realPath + "aa.jpg"));
                }

            }
        }
        model.addAttribute("msg", "大家好,320");
        return "index";
    }

    /**
     * 压缩图片的方法
     * @param read  图片所在路径
     * @param scale  通过比例压缩
     * @return
     */
    public BufferedImage reduce(BufferedImage read,float scale){
        //压缩之后的长度和宽度
        int height = (int) (scale * read.getHeight());
        int width = (int) (scale * read.getWidth());
        BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        finalImage.getGraphics().drawImage(read.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
        return finalImage;
    }
}
